package com.res.share.controller;

import com.google.code.kaptcha.Producer;
import com.res.share.common.Constants;
import com.res.share.common.WebResponse;
import com.res.share.common.exception.BusinessException;
import com.res.share.model.ResUser;
import com.res.share.service.IResStatisticsService;
import com.res.share.service.IResUserService;
import com.res.share.service.MailService;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/res-login")
public class LoginController {

    @Autowired
    private IResUserService resUserService;

    @Autowired
    private MailService mailService;

    @Autowired
    private Producer producer;



    @Autowired
    private IResStatisticsService resStatisticsService;

    private static String[] beforeShuffle = new String[]{"2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F",
            "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a",
            "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
            "w", "x", "y", "z"};

    /**
     * 验证码
     * <img src="http://localhost:80/res-login/captcha.jpg?uuid=111" />
     * uuid :: 前端随机生成
     *
     * @param response response
     * @param uuid     uuid
     */
    @GetMapping("captcha.jpg")
    public void captcha(HttpServletResponse response, String uuid) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //获取图片验证码
        if (StringUtils.isBlank(uuid)) {
            throw new BusinessException("uuid不能为空");
        }
        //生成文字验证码
        String code = producer.createText();
        Cookie cookie = new Cookie(Constants.CAPTCH_CODE_BASE, code);
        cookie.setPath("/");
        cookie.setMaxAge(300);
        //将cookie对象加入response响应
        response.addCookie(cookie);
        BufferedImage image = producer.createImage(code);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }


    /**
     * 发送邮件
     */
    @GetMapping("/sendEmail.html")
    @ResponseBody
    public WebResponse captcha(@RequestParam("email") String email,
                               @RequestParam("title") String title,
                               @RequestParam("type") Integer type,
                               HttpServletResponse response) {

        if (type == null) {
            return WebResponse.ok(-1);
        }
        //注册
        if (type == 1 || type == 3) {
            ResUser resUser = resUserService.checkUserExits(email, 1);
            if (resUser != null) {
                return WebResponse.ok(-2);
            }
        }
        //忘记密码
        if (type == 2) {
            ResUser resUser = resUserService.checkUserExits(email, 1);
            if (resUser == null) {
                return WebResponse.ok(-3);
            }
        }
        String achieveCode = achieveCode();
        mailService.sendMail(email, "资源新球：" + title, achieveCode, response);
        return WebResponse.ok(1);
    }

    /**
     * 登录
     *
     * @return RestResponse
     */
    @PostMapping("/resLogin.html")
    @ResponseBody
    public WebResponse login(HttpServletRequest request,
                             @RequestParam("userName") String userName,
                             @RequestParam("password") String password,
                             @RequestParam("uuid") String uuid,
                             @RequestParam("captchaCode") String captchaCode) {
        boolean captcha = false;
        Cookie[] cookies = request.getCookies();
        if(cookies!=null && cookies.length>0){
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if (name.equalsIgnoreCase(Constants.CAPTCH_CODE_BASE) && cookie.getValue().equalsIgnoreCase(captchaCode)) {
                    captcha = true;
                    break;
                }
            }
        }
        if (!captcha) {
            //验证码不对
            return WebResponse.ok(-1);
        }
        ResUser ResUser = resUserService.findUserDetail(userName);
        if (ResUser == null) {
            //用户在存在
            return WebResponse.ok(-2);
        }
        String userModelPassword = ResUser.getPassword();
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!userModelPassword.equalsIgnoreCase(md5Password)) {
            //密码不正确
            return WebResponse.ok(-3);
        }
        //存储session
        request.getSession().setAttribute(Constants.CURRENT_USER, ResUser.getId());
        return WebResponse.ok();
    }

    /**
     * 注册
     *
     * @param request
     * @param username
     * @param password
     * @param password2
     * @param emailCode
     * @param userEmail
     * @return
     */
    @PostMapping("/user-register.html")
    @ResponseBody
    public WebResponse userRegister(HttpServletRequest request,
                                    @RequestParam("username") String username,
                                    @RequestParam("password") String password,
                                    @RequestParam("password2") String password2,
                                    @RequestParam("emailCode") String emailCode,
                                    @RequestParam("userEmail") String userEmail) {
        Assert.notNull(username, "用户名不能为空");
        Assert.notNull(password, "登录密码不能为空");
        Assert.notNull(password2, "登录密码不能为空");
        Assert.notNull(!password.equalsIgnoreCase(password2), "两次密码不一致！");
        Assert.notNull(emailCode, "邮箱地址不能为空");
        Assert.notNull(userEmail, "邮箱验证码不能为空");
        boolean email = false;
        Cookie[] cookies = request.getCookies();
        if(cookies!=null && cookies.length>0){
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if (name.equalsIgnoreCase(Constants.EMIAL_CODE) && cookie.getValue().equalsIgnoreCase(emailCode)) {
                    email = true;
                    break;
                }
            }
        }

        if (!email) {
            //邮箱验证码失效
            return WebResponse.ok(-1);
        }
        //邮箱已被注册过
        ResUser resUser = resUserService.checkUserExits(userEmail, 1);
        if (resUser != null) {
            return WebResponse.ok(-2);
        }
        //用户名已存在
        ResUser resUserInfo = resUserService.checkUserExits(username, 2);
        if (resUserInfo != null) {
            return WebResponse.ok(-3);
        }
        ResUser saveUserModel = new ResUser();
        saveUserModel.setUserName(username);
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        saveUserModel.setPassword(md5Password);
        saveUserModel.setEmail(userEmail);
        saveUserModel.setLoginTime(new Date());
        int user = resUserService.insertUser(saveUserModel);
        if (user == 1) {
            resStatisticsService.insertUserStatis(saveUserModel.getId());
            return WebResponse.ok(0);
        }
        return WebResponse.ok(-4);
    }

    /**
     * 验证邮箱
     *
     * @param request
     * @param emailCode
     * @param userEmail
     * @return
     */
    @PostMapping("/veryEmail.html")
    @ResponseBody
    public WebResponse veryEmail(HttpServletRequest request,
                                 @RequestParam("emailCode") String emailCode,
                                 @RequestParam("userEmail") String userEmail) {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("status", null);
        resultMap.put("resUrl", null);
        if (StringUtils.isEmpty(emailCode)) {
            resultMap.put("status", -1);
            return WebResponse.ok(resultMap);
        }
        if (StringUtils.isEmpty(emailCode)) {
            resultMap.put("status", -2);
            return WebResponse.ok(resultMap);
        }
        boolean email = false;
        Cookie[] cookies = request.getCookies();
        if(cookies!=null && cookies.length>0){
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if (name.equalsIgnoreCase(Constants.EMIAL_CODE) && cookie.getValue().equalsIgnoreCase(emailCode)) {
                    email = true;
                    break;
                }
            }
        }
        if (!email) {
            //邮箱验证码失效
            resultMap.put("status", -3);
            return WebResponse.ok(resultMap);
        }
        //重置密码
        resultMap.put("resUrl", "/to/resetPassword.html");
        return WebResponse.ok();
    }


    // 随机验证码
    public String achieveCode() {
        List list = Arrays.asList(beforeShuffle);
        Collections.shuffle(list);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            sb.append(list.get(i));
        }
        String afterShuffle = sb.toString();
        String result = afterShuffle.substring(3, 9);
        System.out.print(result);
        return result;
    }
}
